/**
 * Created by Administrator on 2017-12-27.
 */
var windowWidth = require ('../../../js/getWindowSize.js').getWindowSize().windowWidth;
var windowHeight=require ('../../../js/getWindowSize.js').getWindowSize().windowHeight;
var model_img_url = '../../../images/';
var requestMode = require('../../../js/requestsMode.js');
var session = require('../../../js/session.js');
var Tools = require('../../../js/Tools.js');
var QQMapWX = require('../../../js/getUserLocation/qqmap-wx-jssdk.js');
var qqmapsdk;
var translaTionY=windowHeight;
var util = require('../../../js/getUserLocation/util.js');
//var formatLocation = util.formatLocation;
var getWindowHeight=function(){
    var returnHeight=0;
    wx.getSystemInfo({
        success: function (res) {
            returnHeight = res.windowHeight;
        }
    });
    return returnHeight;
};
var WxParse = require('../../../js/wxParse/wxParse.js');
Page({
    data:{
        ///商品名称
        'shopName' : "",
        ///商品默认规格
        'shop_defaultSpecifications' : "",
        ///商品大图片
        'sd_img' : "",
        ///默认单位
        'shopDefault_unit' : "",
        /*判断弹窗是“加入购物车/立即购买”哪种类型*/   /*true 滴啊表加入购物车，false代表立即购买*/
        " joinCarOrBuy":true,
        'horn_img' : model_img_url+'horn.png',
        'list_icon': model_img_url+'deatils_list.png',
        'nowOrder_icon' : model_img_url+'nowOrder.png',
        'operation_img' : [model_img_url+'to_home.png',model_img_url+'join_list.png'],
        'close_alertImg':model_img_url+'close_alert.png',
        ///价格
        'shopDefault_price' : '',
        'hasNumber' :1,
        'buttonAddImg': model_img_url+'add.png',
        'buttonReduceImg' : model_img_url+'reduce.png',
        'addClick' : false,
        'reduceClick' :false,
        'ifShowAlert' :false,
        'alertBgShow':'display:none',
        'alertllHeight':windowHeight,
        'alert_transition':'translateY('+translaTionY+'px);transition: all 0s;',
        'contentShow':false,
        'windowHeight':parseInt(windowHeight),
        ///规格列表
        'shopSpecifications' : [
        ],
        all_price : 0.0,
        activityImg:model_img_url+"openActivity.png",
        activityBoxWidth:"100%",
        animationTime:"transition: all 0s;",
        gang:"/",
        thisTime:null
    },
    getLocation: function () {
        var that = this;
        wx.getLocation({
            success: function (res) {
                qqmapsdk = new QQMapWX({
                    key: 'LLBBZ-C4DHK-ZU4JT-AVFMQ-AIJVO-CQBSU'
                });
                qqmapsdk.reverseGeocoder({
                    location: {
                        latitude: res.latitude,
                        longitude: res.longitude
                    },
                    success: function(res) {
                        console.log("获取省市区 success",res);
                    },
                    fail: function(res) {
                        console.log("获取省市区 fail",res);
                    },
                    complete: function(res) {
                      //  console.log("获取省市区",res);
                    }
                });
            }
        })
    },
    ///界面出现回调
    onLoad:function(res){
        let that = this;
        let detailID = res.id;
        WxParse.emojisInit('[]', "../../../js/wxParse/emojis/", {
            "00": "00.gif",
            "01": "01.gif",
            "02": "02.gif",
            "03": "03.gif",
            "04": "04.gif",
            "05": "05.gif",
            "06": "06.gif",
            "07": "07.gif",
            "08": "08.gif",
            "09": "09.gif",
            "10": "10.gif",
            "11": "11.gif",
            "12": "12.gif",
            "13": "13.gif",
            "14": "14.gif",
            "15": "15.gif",
            "16": "16.gif",
            "17": "17.gif",
            "18": "18.gif",
            "19": "19.gif"
        });
        this.showLoading();
        requestMode.sendRequest("goods/detail","POST",{goods_id:detailID},{skey:session.get("sKey")}).then(
            function (requestSucessRes) {
                that.hideLoading();
                ///网络请求成功
                let responseCode = requestSucessRes.data.code;
                if(responseCode == 200) {
                    ///详情接口请求成功
                    let detailModel = requestSucessRes.data.data;
                    let reachText = detailModel.detail;
                   // detailModel.detail = reachText.replace(/'/g, '"');
                  //  console.log('detailModel',detailModel);
                    let activity_info = detailModel.activity_info.data;
                    let full_cut_info = activity_info.full_cut_info;
                    let goods_give_info = activity_info.goods_give_info;
                    let coupon_info = activity_info.coupon_info;
                    if(detailModel.seckill_start_time != ''){
                        detailModel.IslimitBuy = true;
                        detailModel.seckill_start_time = detailModel.seckill_start_time.replace(/-/g,'/');
                        detailModel.seckill_end_time = detailModel.seckill_end_time.replace(/-/g,'/');
                    }
                    if (detailModel.space.length) {
                        ///如果规格数组有长度
                        ///设置默认规格  和规格数组
                        for (var tempIndex = 0; tempIndex < detailModel.space.length; tempIndex++) {
                            if (tempIndex == 0) {
                                detailModel.space[tempIndex].class = "chose";
                            }else {
                                detailModel.space[tempIndex].class = "notChose";
                            }
                        }
                        if( !detailModel.space[0].space_unit ){
                            that.setData({
                                gang : ''
                            })
                        }
                        that.setData({
                                windowData:detailModel,
                                shop_defaultSpecifications : detailModel.space[0].space_name,
                                shopDefault_price : detailModel.space[0].space_price,
                                all_price : detailModel.space[0].space_price,
                                shopDefault_unit : detailModel.space[0].space_unit,
                                viewpointUuid:detailModel.space[0].space_id,
                                shopSpecifications : detailModel.space,
                                shoppingId : detailModel.id,
                                coupon_info:coupon_info,
                                goods_give_info:goods_give_info,
                                full_cut_info:full_cut_info,
                                expect_time: detailModel.expect_time+'天'
                            }
                        );
                    }
                    ///设置常用数据
                    that.setData({
                        sd_img : detailModel.img,
                        shopName : detailModel.name
                    });
                    //that.interval(that,that.data.windowData);
                    WxParse.wxParse('article', 'html', detailModel.detail, that, 5);
                    that.data.thisTime = setInterval(function(){
                        if(detailModel.IslimitBuy){
                            detailModel.IslimitBuy = true;
                            detailModel.seckill_start_time = detailModel.seckill_start_time.replace(/-/g,'/');
                            detailModel.seckill_end_time = detailModel.seckill_end_time.replace(/-/g,'/');
                            let NumberStartTime = Number(new Date(detailModel.seckill_start_time));
                            let NumberEndTime = Number(new Date(detailModel.seckill_end_time));
                            let NumberNowTime = Number(new Date());
                            if( NumberNowTime < NumberStartTime){
                                let DifferTime = NumberStartTime - NumberNowTime;
                                let leastDay = parseInt( new Date(DifferTime)/1000/3600/24 );
                                let overHour = parseInt( (DifferTime-leastDay*24*3600*1000)/1000/3600 );
                                let leastMinutes =  DifferTime - (overHour*3600*1000) - (leastDay*24*3600*1000);
                                let overMinutes =parseInt( leastMinutes/1000/60  );
                                let leastSeconds = leastMinutes - (overMinutes*60*1000);
                                let overSeconds = parseInt( leastSeconds/1000 );
                                detailModel.leastX =overHour;
                                detailModel.leastF=overMinutes;
                                detailModel.leastM=overSeconds;
                                detailModel.leastT = leastDay;
                                detailModel.startOrEnd = '离活动开始有';
                                that.setData({
                                    acceptBuyLimit : false,
                                    notBeginBuy : true
                                })
                            }else if(NumberNowTime >= NumberStartTime && NumberNowTime <= NumberEndTime){
                                let DifferTime = NumberEndTime - NumberNowTime;
                                let leastDay = parseInt( new Date(DifferTime)/1000/3600/24 );
                                let overHour = parseInt( (DifferTime-leastDay*24*3600*1000)/1000/3600 );
                                let leastMinutes =  DifferTime - (overHour*3600*1000) - (leastDay*24*3600*1000);
                                let overMinutes =parseInt( leastMinutes/1000/60  );
                                let leastSeconds = leastMinutes - (overMinutes*60*1000);
                                let overSeconds = parseInt( leastSeconds/1000 );
                                detailModel.leastX =overHour;
                                detailModel.leastF=overMinutes;
                                detailModel.leastM=overSeconds;
                                detailModel.leastT = leastDay;
                                detailModel.startOrEnd = '活动时间剩余';
                                that.setData({
                                    acceptBuyLimit : true,
                                    timeOut : false
                                })
                            }else if( NumberNowTime > NumberEndTime ){
                                Tools.showErrorToast('活动时间已结束');
                                clearInterval(that.data.thisTime);
                                setTimeout(function () {
                                    wx.reLaunch({
                                        url:'../../index/index'
                                    })
                                },1000);
                                detailModel.IslimitBuy = false;
                                that.setData({
                                    acceptBuyLimit : false,
                                    timeOut : true
                                })
                            }
                            that.setData({
                                windowData : detailModel
                            })
                        }
                    },1000);
                }else {
                    ///详情接口请求失败
                }

            },function(requestFaildRes) {
                that.hideLoading();
            }
        );
        //this.getLocation();
    },
    toList:function(){
        wx.reLaunch({
            url: '../../list/list'
        });
    },
    showLoading:function(){
        wx.showLoading({
            title:'加载中...',
            mask:true
        });
    },
    hideLoading:function(){
        wx.hideLoading();
    },
    seeActivity: function () {
        this.setData({
            activityBoxWidth:'0',
            animationTime:"transition: all 0.3s;"
        })
    },
    closeActivity:function(){
        this.setData({
            activityBoxWidth:'100%',
            animationTime:"transition: all 0.3s;"
        })
    },
    toIndex: function () {
        wx.reLaunch({
            url:'../../index/index'
        })
    },
    submit:function(){
            let that = this;
            let shoppingId = that.data.shoppingId;
            let choseType = that.data.viewpointUuid;
            if(this.data.hasNumber == 0 || this.data.hasNumber==''){
                this.setData({
                    hasNumber:1
                });
                wx.showModal({
                    content:'添加数量最少为一',
                    confirmText: "确定"
                })
            }else{
                let submitType = that.data.joinCarOrBuy;
                if(submitType == true){
                    requestMode.sendRequest("shop-cart/add","POST",{goods_id:shoppingId,number:that.data.hasNumber,space_id:choseType},{sKey:session.get('sKey')}).then(function(res){
                        let code = res.data.code;
                        if( code == 200){
                            that.close_alert();
                            Tools.showSuccessInfoToast("已加入购物车");
                        }else{
                            Tools.showErrorToast(res.data.message);
                        }
                    },function(){
                        Tools.showWrongNetWorkToast();
                    })
                }else{
                    let currentSelectShop = that.data.windowData;
                    currentSelectShop['number'] = parseInt(that.data.hasNumber);//商品数量
                    let shopSpecifications = that.data.shopSpecifications;
                    for( let i in shopSpecifications){
                        if(shopSpecifications[i].class == 'chose') {
                            //找到对应选中的那个规格
                            currentSelectShop["space_id"] = shopSpecifications[i].space_id;
                            currentSelectShop["space_price"] = shopSpecifications[i].space_price;
                            currentSelectShop["space_name"] = shopSpecifications[i].space_name;
                            currentSelectShop["space_unit"] = shopSpecifications[i].space_unit;
                            currentSelectShop["space_stock"] = shopSpecifications[i].space_stock;
                            currentSelectShop["space_sold"] = shopSpecifications[i].space_sold;
                            currentSelectShop['goods_id'] = that.data.shoppingId;
                            break;
                        }
                    }
                    let data=[currentSelectShop];
                    wx.navigateTo({
                        url:'../../mines/confirmationOrder/confirmationOrder?shopArray='+JSON.stringify(data)+'&shop_cart_ids='
                    })
                }
            }
    },
    close_alert:function(){
        const   This=this;
        const intHeight=getWindowHeight();
        This.setData({
            alertllHeight:intHeight
        });
        This.setData({
            'alert_transition':'translateY('+intHeight+'px);transition: all 0.5s;'
        });
        setTimeout(function(){
            This.setData({
                ifShowAlert:false
            })
        },10);
        setTimeout(function(){
            This.setData({
                alertBgShow:'display:none'
            });
        },300)
    },
    body_closeAlert:function(){
        const   This=this;
        const intHeight=getWindowHeight();
        This.setData({
            alertllHeight:intHeight
        });
        This.setData({
            'alert_transition':'translateY('+intHeight+'px);transition: all 0.5s;'
        });
        setTimeout(function(){
            This.setData({
                ifShowAlert:false
            })
        },10);
        setTimeout(function(){
            This.setData({
                alertBgShow:'display:none'
            });
        },300)
    },
    tap_add:function(){
        let This=this;
        This.setData({
            addClick:true
        });
        let limitCount = This.data.windowData.seckill_limit;
        if(This.data.hasNumber>=1){
            This.setData({
                hasNumber:parseInt(This.data.hasNumber)+1
            });
            if(limitCount){
                if(This.data.hasNumber > limitCount){
                    This.setData({
                        hasNumber:limitCount
                    })
                }
            }
            this.reloadPrice();
        }
        setTimeout(function(){
            This.setData({
                addClick:false
            });
        },200)
    },
    tap_reduce:function(){
        if (this.data.hasNumber <= 1)
        {
            return;
        }
        let This=this;
        this.setData({
            reduceClick:true
        });
        if(this.data.hasNumber>1){
            This.setData({
                hasNumber:parseInt(This.data.hasNumber)-1
            });
            this.reloadPrice();
        }
        setTimeout(function(){
            This.setData({
                reduceClick:false
            });
        },200)
    },
    numberChange:function(e){
        const  This=this;
        let newCount = e.detail.value;
        let limitBuyCount = This.data.windowData.seckill_limit;
        if(This.data.windowData.IslimitBuy == true){
            if(Number(newCount) >= Number(limitBuyCount)){
                newCount = limitBuyCount;
            }
        }
        if(!newCount){
            newCount = 1;
        }
        This.setData({
            hasNumber:newCount
        });
        this.reloadPrice();
    },
    big_img_load:function(e){
        const default_imgwidth = e.detail.width,
            default_imgheight = e.detail.height,
            default_promotion_ratio = default_imgwidth / default_imgheight;
        const default_need_height = windowWidth/default_promotion_ratio;
        this.setData({
            rel_height: default_need_height,
            rel_width:windowWidth
        });
    },
    ///获取当前选中商品对应规格的价格
    getCurrentPerPrice : function () {
        const allType = this.data.shopSpecifications;
        var currentPrice = 0.0;
        for(var i=0;i<allType.length;i++){
            if(allType[i].class == 'chose'){
                return allType[i].space_price;
            }
        }
    },
    ///刷新弹窗价格
    reloadPrice : function () {
        var  perPrice = this.getCurrentPerPrice();
        var  totalPrice = this.data.hasNumber * perPrice;
        this.setData(
            {
                all_price : totalPrice.toFixed(2),
                shopDefault_price : perPrice
            }
        );
    },
    choseThisType:function(e){
        var clickIndex=e.currentTarget.dataset.index;
        const shopSpecifications=this.data.shopSpecifications;
        let viewpointUuid = e.currentTarget.dataset.viewpointUuid;
        for(var i=0;i<shopSpecifications.length;i++){
            if(i==clickIndex){
                shopSpecifications[i].class='chose';
            }else{
                shopSpecifications[i].class='notChose';
            }
        }
        this.setData({
            shopSpecifications:shopSpecifications,
            viewpointUuid:viewpointUuid
        });
        this.reloadPrice();
    },
    /*立即购买*/
    goBuy:function(){
        const   This=this;
        const intHeight=getWindowHeight();
        function animate(){
            This.setData({
                joinCarOrBuy:false,
                alertllHeight:intHeight,
                'alert_transition':'translateY('+intHeight+'px);transition: all 0s;'
            });
            This.setData({
                alertBgShow:'display:block'
            });
            setTimeout(function(){
                This.setData({
                    ifShowAlert:true
                })
            },10);
            setTimeout(function(){
                This.setData({
                    'alert_transition':'translateY('+0+'px);transition: all 0.2s;'
                })
            },10)
        }
        if(This.data.windowData.IslimitBuy == true){
            if(This.data.acceptBuyLimit == true){
                animate();
            }else{
                if(This.data.timeOut == true){
                    Tools.showErrorToast('活动已结束');
                }else if(This.data.notBeginBuy == true){
                    Tools.showErrorToast('活动尚未开始');
                }
                return;
            }
        }else{
            animate()
        }
    },
    /*加入购物车操作*/
    joinCar:function(){
        const   This=this;
        const intHeight=getWindowHeight();
        function joincarAnimate(){
            This.setData({
                alertllHeight:intHeight,
                joinCarOrBuy:true,
                'alert_transition':'translateY('+intHeight+'px);transition: all 0s;'
            });
            This.setData({
                alertBgShow:'display:block'
            });
            setTimeout(function(){
                This.setData({
                    ifShowAlert:true
                })
            },10);
            setTimeout(function(){
                This.setData({
                    'alert_transition':'translateY('+0+'px);transition: all 0.2s;'
                })
            },10)
        }
        if(This.data.windowData.IslimitBuy == true){
            if(This.data.acceptBuyLimit == true){
                joincarAnimate();
            }else{
                if(This.data.timeOut == true){
                    Tools.showErrorToast('活动已结束');
                }else if(This.data.notBeginBuy == true){
                    Tools.showErrorToast('活动尚未开始');
                }
                return;
            }
        }else{
            joincarAnimate()
        }

    },
    ///加入长购清单
    addTo_awaysBuyList : function () {
        Tools.showLoaddingDefault();
        let shoppingId = this.data.shoppingId;
        let space_id = this.data.viewpointUuid;
        if(this.data.windowData.IslimitBuy == true){
            Tools.showErrorToast('不允许此操作');
            return;
        }
        requestMode.sendRequest("always-buy/create","POST",{"goods_id":shoppingId,"space_id":space_id},{sKey:session.get("sKey")}).then(
            function (requestSucess)
            {
                let statusCode =  requestSucess.data.code;
                if (statusCode == 200)
                {
                    Tools.showSuccessInfoToast("已添加");
                }else
                {
                    Tools.showErrorToast(requestSucess.data.message);
                }
            },function (requestWrong)
            {
                 Tools.showWrongNetWorkToast();
            }
        );
    },
    previewImage: function(e){
        let pictures = e.currentTarget.dataset.src;
        wx.previewImage({
            urls: [pictures],
            success:function(seeMaxImgSuccess){
                // console.log('查看success',seeMaxImgSuccess)
            },
            fail: function () {
                // console.log('查看fail')
            }
        });
    },
});